<!-- TeamAvatarUploader.vue -->
<template>
  <div class="team-avatar-uploader">
    <van-image
        :src="avatarUrl"
        @click="openUploader"
        fit="cover"
        shape="square"
        width="90px"
        height="90px"
        :class="{ 'is-uploading': isUploading }"
    />
    <van-popup v-model="showUploader" position="bottom">
      <van-uploader
          v-model="tempFileList"
          :before-read="beforeRead"
          :after-read="afterRead"
          :max-count="1"
          @oversize="onOversize"
          :deletable="false"
      />
      <div class="buttons">
        <van-button size="small" type="primary" @click="submit" :loading="isUploading">确认</van-button>
        <van-button size="small" type="default" @click="cancel">取消</van-button>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watchEffect } from 'vue';
import { Toast } from 'vant';
import axios from 'axios';

interface FileItem extends File {
  url?: string;
}

const props = defineProps<{
  teamId: number;
  initialAvatarUrl: string;
  creatorId: number;
  currentUser: { id: number } | undefined;
}>();

const showUploader = ref(false);
const tempFileList = ref<FileItem[]>([]);
const isUploading = ref(false);

const avatarUrl = computed(() => {
  return props.initialAvatarUrl || '';
});

const openUploader = () => {
  if (props.currentUser?.id === props.creatorId) {
    showUploader.value = true;
  } else {
    Toast.fail('只有队伍创建者才能修改头像');
  }
};

const beforeRead = (file: File) => {
  const maxSize = 5 * 1024 * 1024; // 5MB
  if (file.size > maxSize) {
    Toast.fail('头像文件过大，请选择小于5MB的图片');
    return false;
  }
  return true;
};

const afterRead = async (file: File) => {
  isUploading.value = true;
  try {
    const formData = new FormData();
    formData.append('id', String(props.teamId));
    formData.append('teamAvatar', file);
    await axios.post('/update/teamAvatar', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    });
    Toast.success('队伍头像更新成功');
    showUploader.value = false;
    isUploading.value = false;
  } catch (error) {
    Toast.fail('队伍头像更新失败');
    isUploading.value = false;
  }
};

const onOversize = () => {
  Toast.fail('头像文件过大，请选择小于5MB的图片');
};

const submit = () => {
  if (tempFileList.value.length === 0) {
    Toast.fail('请选择要上传的头像');
    return;
  }
  afterRead(tempFileList.value[0]);
};

const cancel = () => {
  showUploader.value = false;
  tempFileList.value = [];
};
</script>

<style scoped>
.buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}
</style>